import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { getTokenAUTH } from './auth'
import { Message } from '@arco-design/web-vue'

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 10 * 1000,
  headers: {
    'Content-Type': 'application/json',
  },
})

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const isToken = (config.headers || {}).isToken === false
    if (getTokenAUTH() && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getTokenAUTH()
    }
    return config
  },
  (error) => {
    console.log('request error', error)
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response) => {
    // 处理文件流响应
    if (response.config.responseType === 'blob' || response.data instanceof Blob) {
      return response.data
    }

    const { code, message } = response.data
    if (code === 200) {
      return response.data
    } else {
      Message.error(message || '请求失败')
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  (error) => {
    let errorMessage = '请求错误'
    if (error.response) {
      switch (error.response.status) {
        case 400:
          errorMessage = '请求参数错误'
          break
        case 401:
          errorMessage = '未授权，请登录'
          break
        case 403:
          errorMessage = '拒绝访问'
          break
        case 404:
          errorMessage = '请求地址不存在'
          break
        case 500:
          errorMessage = '服务器内部错误'
          break
        default:
          errorMessage = error.response.data?.message || error.message
      }
    } else if (error.request) {
      errorMessage = '请求超时或网络异常'
    }
    Message.error(errorMessage)
    return Promise.reject(error)
  },
)

// 封装请求方法
const request = <T>(config: AxiosRequestConfig): Promise<T> => {
  const { method, url, data, params, ...restConfig } = config
  if (!url) return Promise.reject(new Error('URL is required'))
  switch (method?.toLowerCase()) {
    case 'get':
      return service.get(url, { params, ...restConfig })
    case 'post':
      return service.post(url, data, restConfig)
    case 'put':
      return service.put(url, data, restConfig)
    case 'delete':
      return service.delete(url, { ...restConfig })
    default:
      return Promise.reject(new Error('Unsupported method'))
  }
}

export default request
